package com.chromatic.competition.view.profile;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chromatic.competition.R;
import com.chromatic.competition.adapter.UserPostsAdapter;
import com.chromatic.competition.model.UserPost;
import com.chromatic.competition.utils.UserLoginStatus;
import com.chromatic.competition.utils.UserPostManager;

import java.util.ArrayList;
import java.util.List;

public class MyPostActivity extends AppCompatActivity {
    private final UserPostManager userPostManager = new UserPostManager();
    private UserPostsAdapter userPostAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_post);

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        userPostAdapter = new UserPostsAdapter();
        recyclerView.setAdapter(userPostAdapter);

        List<UserPost> userPosts = new ArrayList<>();

        // 获取用户自己的帖子
        getUserPosts();

        // 可选：如果帖子可以动态更新，可以设置下拉刷新功能
        SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            getUserPosts();
            swipeRefreshLayout.setRefreshing(false);
        });

        ImageView backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed(); // 调用系统返回操作
            }
        });
    }
    @SuppressLint("NotifyDataSetChanged")
    private void getUserPosts() {
        int userId = new UserLoginStatus(this).getCurrentUserId();
        userPostManager.getUserPostsByUserId(userId, new UserPostManager.UserPostCallback() {
            @Override
            public void onSuccess(List<UserPost> userPosts) {
                // 在回调方法中处理帖子获取成功的情况
                runOnUiThread(() -> {
                    userPostAdapter.setUserPosts(userPosts);
                    userPostAdapter.notifyDataSetChanged();
                });
            }
            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> Toast.makeText(MyPostActivity.this, "获取用户帖子失败：" + errorMessage, Toast.LENGTH_SHORT).show());
            }
        });
    }
}